<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('成绩记录')" />
    <style>
        .main-ctn{
            padding: 10px 25px;
            height: 100%;
        }
        .main-ctn .ibox{
            margin: 10px 0;
        }
        #place_form{
            margin-left: -20px;
        }

        .register-list{
            display: flex;
            overflow-x: auto;
            position: relative;
        }
        .register{
            cursor: pointer;
            border-radius: 4px;
            margin: 4px 10px 4px 0px;
            padding: 4px;
            white-space: nowrap;
        }
        .register:hover{
            background: #23c6c8;
            color: #fff;
            opacity: .6;
        }
        .register.active{
            background: #23c6c8;
            color: #fff;
        }
        .tool-bar{
            padding: 8px;
        }
        #score_table th, #score_table td{
            text-align: center;
        }
        #score_table .radio{
            margin: 0;
            padding-right: unset;
        }
        #score_table .radio label{
            padding-left: unset;
        }
        #score_table input{
            text-align: center;
        }
        .checkbox label, .radio label{
            padding-left: unset;
        }

        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
        }
        input[type="number"]{
            -moz-appearance: textfield;
        }

    </style>
</head>
<body class="gray-bg">
     <div class="main-ctn">
        <div class="row">
            <div class="col-sm-12 search-collapse list-ctn">
                <form id="place_form">
                    <div class="select-list">
                        <ul>
                            <li>
                                <p>场地：</p>
                                <select id="select2_place" class="form-control" onchange="refreshRegisterList()">
                                    <option th:each="place : ${placeList}" th:text="${place.name}" th:value="${place.id}"></option>
                                </select>
                            </li>
                            <li>
                                <p>选手：</p>
                                <input type="text" autocomplete="off" name="playerName"/>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="searchPlayer()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="resetSearch()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="col-sm-12 search-collapse list-ctn">
                <div class="register-list">

                </div>
            </div>

            <div class="col-sm-12 search-collapse tool-bar">
                <a class="btn btn-sm btn-info" onclick="nextRegister()">
                    <i class="fa fa-step-forward"></i> 下一个
                </a>
                <a class="btn btn-sm btn-primary" onclick="sendToScore()">
                    <i class="fa fa-step-forward"></i> 发送打分
                </a>
                <a class="btn btn-sm btn-warning" onclick="sendToScreenScore()">
                    <i class="fa fa-tv"></i> 投屏成绩
                </a>
                <a class="btn btn-sm btn-warning" onclick="sendToScreenScore2()">
                    <i class="fa fa-tv"></i> 投屏成绩2
                </a>
                <a class="btn btn-sm btn-danger" onclick="clearRegisterScore()">
                    <i class="fa fa-remove"></i> 清除成绩
                </a>

            </div>
        </div>

         <div class="row">
             <div id="score_ctn" class="col-sm-12 select-table">

             </div>
         </div>

    </div>
    <th:block th:include="include :: footer" />

    <script id="tmpl_register" type="text/template">
    {{each(i, v) registerList}}
        <div onclick="clickRegister(this)" class="register" data-register-id="${v.id}" data-register-player-name="${v.playerName}">
            ${v.session}-${v.odr} ${v.playerName}
        </div>
    {{/each}}
    </script>

    <script id="tmpl_score_ctn" type="text/template">
     <div class="ibox">
         <div class="ibox-title">第${register.session}轮 第${register.odr}号 --- ${register.groupName} --- ${register.worksName}</div>
         <div class="ibox-content">
             <table id="score_table" class="table table-bordered">
                 <tbody>
                    <tr>
                        <td rowspan="2">Fig</td>
                        <td colspan="${judgeList.length}">裁判员评分</td>
                        <td rowspan="2">平均分</td>
                    </tr>
                    <tr>
                        {{each(i,j) judgeList}}
                        <td>${j.name}</td>
                        {{/each}}
                    </tr>
                    {{each(i,r) matchValueList}}
                    <tr class="match-value" data-match-value-id="${r.id}">

                        <td width="6%">${r.name}</td>
                        {{each(i,j) judgeList}}
                        <td width="6%">
                            <input onchange="scoreChange(this)" data-match-value-id="${r.id}" data-judge-id=${j.id} name="score" class="form-control" type="number" autocomplete="off">
                        </td>
                        {{/each}}

                        <td width="6%" class="value-score"></td>
                    </tr>
                    {{/each}}

                    <tr class="sum-value">

                        <td width="6%">总分</td>
                        {{each(i,j) judgeList}}
                        <td width="6%">
                            <span class="judge-score" data-judge-id="${j.id}"></span>
                        </td>
                        {{/each}}

                        <td width="6%" class="value-score"></td>
                    </tr>


                    <tr>
                        <td>备注</td>
                        <td colspan="${judgeList.length}">
                        <textarea id="remark" onchange="remarkChange()" class="form-control"
                          autocomplete="off">${register.remark}</textarea>
                        </td>
                    </tr>

                    <tr class="last-value">
                        <td width="6%">最终成绩</td>
                        <td width="6%" colspan="${judgeList.length}" class="value-score"></td>
                    </tr>

                 </tbody>
             </table>
         </div>
     </div>
    </script>

    <script th:inline="javascript">
        var prefix = ctx + "js/score";
        var wsUrl = [[${wsUrl}]];

        function searchPlayer(){
            var name = $("input[name='playerName']").val();
            var no = $("input[name='registerNo']").val();
            $(".register-list .register").addClass("hide");
            $(".register-list .register").each(function (index, item) {
                var playerName = $(item).attr("data-register-player-name");
                var registerNo = $(item).attr("data-register-no");
                if(playerName.indexOf(name) >= 0 && registerNo.indexOf(no) >= 0){
                    $(item).removeClass("hide");
                }
            });
        }

        function resetSearch(){
            $("input[name='playerName']").val("");
            $(".register-list .register").removeClass("hide");
        }

        refreshRegisterList()
        function refreshRegisterList(){
            var placeId = $("#select2_place").val();
            if(placeId){
                $.get(prefix + "/getRegisterList", {placeId}, function (res) {
                    $(".register-list").empty();
                    if(res.data.length > 0){
                        $("#tmpl_register").tmpl({registerList: res.data}).appendTo(".register-list");
                        nextRegister();
                    }else {
                        $(".register-list").text("没有报名信息");
                        refreshRegisterInfo();
                    }

                });
            }
        }

        function clickRegister(evt){
            $(".register-list .register").removeClass("active");
            $(evt).addClass("active");
            refreshRegisterInfo();
        }

        function nextRegister() {

            var $next;
            var $register = $(".register-list .register.active");
            if($register.length > 0){
                $next = $register.next(".register");
                if($next.length == 0){
                    $next = $(".register-list .register").first();
                }
            }else {
                $next = $(".register-list .register").first();
            }
            $(".register-list .register").removeClass("active");

            if($next.length > 0){
                $next.addClass("active");
                var offsetLeft = $next[0].offsetLeft;
                var selfWidth = $next.width();
                var parentWidth = $(".register-list").width();
                if(offsetLeft + selfWidth >= parentWidth){
                    $(".register-list").animate({
                        scrollLeft: offsetLeft + selfWidth - (parentWidth / 2)
                    }, 200);
                }else {
                    $(".register-list").scrollLeft(0);
                }
                refreshRegisterInfo();
            }
        }

        function refreshRegisterInfo() {
            var $register = $(".register-list .register.active");
            var registerId = $register.attr("data-register-id");

            $("#score_ctn").empty();
                if(registerId){
                    $.get(prefix + "/getRegisterInfo", { registerId }, function (res) {
                        $("#tmpl_score_ctn").tmpl(res.data).appendTo("#score_ctn");
                        refreshRegisterScore();
                    });
                }
        }

        function refreshRegisterScore() {
            var dfd = $.Deferred();
            var $register = $(".register-list .register.active");
            var registerId = $register.attr("data-register-id");
            if(!registerId){
                return;
            }
            $.get(prefix + "/getRegisterScore", { registerId }, function (res) {
                var scoreMap = res.data.scoreMap;
                $("#score_ctn input[name='score']").each(function () {
                    var itemValueId = $(this).attr("data-match-value-id");
                    var judgeId = $(this).attr("data-judge-id");
                    var key = itemValueId + "-" + judgeId;
                    $(this).val(scoreMap[key]);
                });
                computeScores();
                dfd.resolve();
            });
            return dfd;
        }

        function scoreChange(evt) {
            var $register = $(".register-list .register.active");
            var registerId = $register.attr("data-register-id");
            var matchValueId = $(evt).attr("data-match-value-id");
            var judgeId = $(evt).attr("data-judge-id");
            var value = $(evt).val();
            $.post(prefix + "/saveScore", { registerId, matchValueId, judgeId, value }, function (res) {
                if (res.code == web_status.SUCCESS) {
                    computeScores();
                    $.modal.msgSuccess("成绩保存成功");
                }else {
                    $.modal.msgError("成绩保存失败");
                }
            });
        }


        function computeScores() {
            var sumValueScore = 0;
            var hasScore = false;
            var $values = $("#score_table tr.match-value");
            $values.each(function () {
                var sumValue = 0;
                var $scores = $(this).find("input[name='score']");
                $scores.each(function () {
                    var value = $(this).val();
                    if(value.length > 0){
                        sumValue += parseFloat(value);
                        hasScore = true;
                    }
                });
                var valueScore = sumValue / $scores.length;

                if(hasScore){
                    $(this).find(".value-score").text(valueScore.toFixed(2));
                }

                sumValueScore += valueScore;
            });

            if(!hasScore){
                return;
            }

            var judgeScores = [];
            $("#score_table .judge-score").each(function () {
                var sumValue = 0;
                var judgeId = $(this).attr("data-judge-id");
                var $scores = $("#score_table").find("input[data-judge-id="+ judgeId +"]");
                $scores.each(function () {
                    var value = $(this).val();
                    if(value.length > 0){
                        sumValue += parseFloat(value);
                    }
                });
                $(this).html(sumValue.toFixed(2));
                judgeScores.push(sumValue);
            });

            $(".sum-value .value-score").html(sumValueScore.toFixed(2));

            // 最终成绩，大于3个评委去掉最高最低
            judgeScores.sort(function (a, b) {
                return a - b;
            });
            if(judgeScores.length > 3){
                judgeScores.shift();
                judgeScores.pop();
            }
            var lastSumValue = judgeScores.reduce(function (a, b) {
                return a + b;
            });
            var lastScore = lastSumValue / judgeScores.length;
            var remark = $("#remark").val();
            if(!remark){
                remark = 0;
            }
            lastScore = lastScore + parseFloat(remark);
            var lastTxt = (lastSumValue / judgeScores.length).toFixed(2) + " + " + remark + " = " +  lastScore.toFixed(2);
            $(".last-value .value-score").html(lastTxt);

        }


        function sendToScore() {
            var $register = $(".register-list .register.active");
            var registerId = $register.attr("data-register-id");
            $.get(prefix + "/sendToScore", { registerId}, function (result) {
                if (result.code == web_status.SUCCESS) {
                    $.modal.msg("发送成功");
                } else {
                    $.modal.alertWarning("发送失败");
                }
            });
        }

        function sendToScreenScore() {
            var $register = $(".register-list .register.active");
            var registerId = $register.attr("data-register-id");
            $.get(prefix + "/sendToScreenScore", { registerId}, function (result) {
                if (result.code == web_status.SUCCESS) {
                    $.modal.msg("发送成功");
                } else {
                    $.modal.alertWarning("发送失败");
                }
            });
        }

        function sendToScreenScore2() {
            var $register = $(".register-list .register.active");
            var registerId = $register.attr("data-register-id");
            $.get(prefix + "/sendToScreenScore2", { registerId}, function (result) {
                if (result.code == web_status.SUCCESS) {
                    $.modal.msg("发送成功");
                } else {
                    $.modal.alertWarning("发送失败");
                }
            });
        }

        function clearRegisterScore() {
            $.modal.confirm("确认要清除当前报名成绩吗？", function() {
                var $register = $(".register-list .register.active");
                var registerId = $register.attr("data-register-id");
                $.post(prefix + "/clearRegisterScore", { registerId}, function (result) {
                    if (result.code == web_status.SUCCESS) {
                        refreshRegisterInfo();
                        $.modal.msg("清除成功");
                    } else {
                        $.modal.alertWarning("清除失败");
                    }
                });
            });
        }

        function remarkChange(evt) {
            var remark = $("#remark").val();
            var $register = $(".register-list .register.active");
            var registerId = $register.attr("data-register-id");
            $.post(prefix + "/updateRemark", {registerId, remark}, function (res) {
                if (res.code == web_status.SUCCESS) {
                    computeScores();
                    $.modal.msgSuccess("保存成功");
                } else {
                    $.modal.msgError("保存失败");
                }
            });
        }


        socket();
        function socket() {

            if (window.WebSocket && window.MozWebSocket) {
                console.log("浏览器不支持websocket")
            }

            var ws = new WebSocket(wsUrl);

            // 收到消息后触发
            ws.onmessage = function (msg) {
                // 服务器连接后默认发送online字符串
                if(msg.data == "pong"){
                    return;
                }
                var data = JSON.parse(msg.data);
                switch (data.type) {
                    case "refreshScore":
                        refreshRegisterScore();
                        break;

                }
            }

            //建立连接后触发
            ws.onopen = function () {
                console.log("ws连接成功");
            };

            // 关闭连接时候触发
            ws.onclose = function () {
                reconnect();
            };

            //发生错误的时候触发
            ws.onerror = function () {
                reconnect();
            };
        }

        // 每隔5秒重连
        var lock = false;
        function reconnect() {
            if (lock) return;
            lock = true;
            setTimeout(function () {
                socket();
                lock = false;
            }, 5 * 1000);
        }

    </script>
</body>
</html>